#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include "err.hpp"
using namespace std;

static void usage(char* proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport\n" << endl;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "create socket error" << endl;
        exit(SOCKET_ERR);
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &server.sin_addr);

    int cnt = 5;
    while (connect(sock, (struct sockaddr*)&server, sizeof(server)) != 0)
    {
        sleep(1);
        cout << "正在尝试重新连接，重连次数还有：" << cnt-- << endl; 
        if (cnt <= 0) break;
    }
    if (cnt <= 0)
    {
        cerr << "连接失败..." << endl;
        exit(CONNECT_ERR);
    }
    char buffer[1024];
    while (true)
    {
        string line;
        cout << "Enter>>> ";
        getline(cin, line);

        write(sock, line.c_str(), line.size());

        ssize_t s = read(sock, buffer, sizeof(buffer)-1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "server echo >>> " << buffer << endl;
        }
        else if (s == 0)
        {
            cerr << "server quit" << endl;
            break;
        }
        else
        {
            cerr << "server error" << endl;
            break;
        }
    }
    close(sock);
    return 0;
}